<style type="text/css">
	li#previous.disabled a {color:#CCC}
	li#next.disabled a {color:#CCC}
</style>
<div class="row">
<div class="col-md-12">
	<div style="float:left;margin:10px 5px;">
	<form class="form-inline">
		<div class="form-group">
			<label for="type">查询方式: </label>
		    <label class="radio-inline" data-toggle='tooltip' title="按照偏移量查询消息,最多检索5000条">
			    <input type="radio" name="searchType" onclick="changeSearchType('offset')" checked="checked">偏移量
			</label>
		    <label class="radio-inline" data-toggle='tooltip' title="按照key查询消息，最多可查时间段内的${brokerSize*64}条">
		    	<input type="radio" name="searchType" onclick="changeSearchType('key')">key
		    </label>
			<label class="radio-inline" data-toggle='tooltip' title="按照时间段查询消息,最多检索5000条">
			    <input type="radio" name="searchType" onclick="changeSearchType('time')">时间段
			</label>
			<label class="radio-inline" data-toggle='tooltip' title="按照消息id查询">
		    	<input type="radio" name="searchType" onclick="changeSearchType('msgId')">消息id
		    </label>
		</div>
	</form>
	</div>
	<div style="float:right;margin:10px 0px;">
	<form class="form-inline" id="msgSearchForm">
		<div>
			<!-- 偏移量查询 -->
			<div class="form-group offset">
				<label for="offsetStart" data-toggle='tooltip' title="参考生产详情里的最小偏移量"> 起始偏移量: </label>
				<input id="offsetStart" name="offsetStart" type="text" class="form-control" style="width:120px;" value="${response.result.minOffset?c}">
			</div>
			<div class="form-group offset">
	  			<label for="offsetEnd" data-toggle='tooltip' title="参考生产详情里的最大偏移量"> 结束偏移量: </label>
				<input id="offsetEnd" name="offsetEnd" type="text" class="form-control" style="width:120px;" value="${response.result.maxOffset?c}">
			</div>
			<div class="form-group offset">
	    	    <input type="text" class="form-control" id="offsetKey" name="offsetKey" value="${response.result.key!}" placeholder="关键字，支持模糊匹配">
	  	    </div>
			<!-- 时间段查询 -->
			<div class="form-group time" style="display:none;">
				<label for="startTimePicker"> 开始时间: </label>
				<input id="startTimePicker" type="text" class="Wdate form-control" onclick="WdatePicker({ dateFmt: 'yyyy-MM-dd HH:mm:ss',maxDate:'%y-%M-%d',minDate:'%y-%M-{%d-5}',onpicked:function(){timeChange('startTime')}})" style="width:180px;height:34px;cursor:pointer;" readonly="readonly"
	  								value="${response.result.start?number_to_datetime?string("yyyy-MM-dd HH:mm:ss")}">
	  			<input type="hidden" name="startTime" id="startTime" value="${response.result.start?c}">
	  			<label for="endTimePicker"> 结束时间: </label>
				<input id="endTimePicker" type="text" class="Wdate form-control" onclick="WdatePicker({ dateFmt: 'yyyy-MM-dd HH:mm:ss',maxDate:'%y-%M-%d',minDate:'%y-%M-{%d-5}',onpicked:function(){timeChange('endTime')}})" style="width:180px;height:34px;cursor:pointer;" readonly="readonly"
	  								value="${response.result.end?number_to_datetime?string("yyyy-MM-dd HH:mm:ss")}">
	  			<input type="hidden" name="endTime" id="endTime" value="${response.result.end?c}">
			</div>
			<div class="form-group time" style="display:none;">
	    	    <input type="text" class="form-control" id="key" name="key" value="${response.result.key!}" placeholder="关键字，支持模糊匹配">
	  	    </div>
			<!-- 消息查询 -->
	  	    <div class="form-group msgId" style="display:none;">
	    	    <input type="text" class="form-control" id="msgId" name="msgId" value="${response.result.msgId!}" placeholder="消息id">
	  	    </div>
	  	    <!-- key查询 -->
	  	    <div class="form-group key" style="display:none;">
				<label for="keyStartTimePicker"> 开始时间: </label>
				<input id="keyStartTimePicker" type="text" class="Wdate form-control" onclick="WdatePicker({ dateFmt: 'yyyy-MM-dd HH:mm:ss',maxDate:'%y-%M-%d',minDate:'%y-%M-{%d-6}',onpicked:function(){timeChange('keyStartTime')}})" style="width:180px;height:34px;cursor:pointer;" readonly="readonly"
	  								value="${response.result.start?number_to_datetime?string("yyyy-MM-dd 00:00:00")}">
	  			<input type="hidden" name="keyStartTime" id="keyStartTime">
	  			<label for="keyEndTimePicker"> 结束时间: </label>
				<input id="keyEndTimePicker" type="text" class="Wdate form-control" onclick="WdatePicker({ dateFmt: 'yyyy-MM-dd HH:mm:ss',maxDate:'%y-%M-%d',minDate:'%y-%M-{%d-6}',onpicked:function(){timeChange('keyEndTime')}})" style="width:180px;height:34px;cursor:pointer;" readonly="readonly"
	  								value="${.now?string("yyyy-MM-dd HH:mm:ss")}">
	  			<input type="hidden" name="keyEndTime" id="keyEndTime" value="${response.result.end?c}">
			</div>
	  	    <div class="form-group key" style="display:none;">
	    	    <input type="text" class="form-control" id="msgKey" name="msgKey" placeholder="消息key">
			</div>
	  	    
			<!-- 时间段查询参数 -->
	  	    <input type="hidden" id="cid" name="cid" value="${response.result.cid}">
	  	    <input type="hidden" id="topicDiv" name="topic" value="${response.result.topic}">
	  	    <input type="hidden" id="append" name="append" value="false">
	  	    <input type="hidden" id="messageParam" name="messageParam" value="${response.result.serialize()}">
			<button type="button" data-toggle='tooltip' title="如果查不到数据请使用偏移量查询" onclick="searchMessage(false)" class="btn btn-search time" style="display:none;"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></button>
			<!-- 消息查询 -->
			<button type="button" onclick="viewMessage()" class="btn btn-search msgId" style="display:none;"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></button>
			<!-- key查询 -->
			<button type="button" onclick="searchKeyMessage()" class="btn btn-search key" style="display:none;"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></button>
			<!-- 偏移量查询 -->
			<button type="button" onclick="showMoreSearchCondition()" class="btn offset" data-toggle="tooltip" title="单击展开更多搜索项"><span class="glyphicon glyphicon-filter" aria-hidden="true"></span></button>
			<button type="button" onclick="searchOffsetMessage(false)" class="btn btn-search offset"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></button>
			<!-- 消息重发 -->
			<#if owner == 1>
				<button type="button"  data-toggle='tooltip' title="重发消息" onclick="resendMessageTip()" class="btn"><span class="glyphicon glyphicon-send"></span></button>
			</#if>
		</div>
		<div class="form-group hide" id ="moreSearchCondition" style="margin-top:10px">
			<label style="margin-left:23px"> broker: </label>
			<select id="brokerNameSearchSelect" class="selectpicker" name="toBrokerName" onchange="brokerNameSelectChange(this)"></select>
			<label style="margin-left:27px"> queue: </label>
			<select id="queueSearchSelect" class="selectpicker" name="toQueue" onchange="queueSelectChange(this)">
			<option value="-1">全部</option>
			</select>
		</div>
	</form>
	</div>
	<table id="dataTable" class="table table-striped table-hover <#if owner == 1>tr-pointer</#if>" style="margin-top: 0px;word-break:break-all; word-wrap:break-all;">
		<colgroup>
			<col width="50px">
			<col width="130px">
			<col width="160px">
			<col>
			<col width="120px">
			<col width="80px">
			<col width="50px">
		</colgroup>
		<thead>
			<tr>
				<td>序号</td>
				<td>客户端</td>
				<td>发送时间</td>
				<td>消息</td>
				<td>keys</td>
				<td>tags</td>
				<td>详情</td>
			</tr>
		</thead>
		<tbody>
			<tr class="no_more_data"><td colspan=7 class="text-center">暂无数据</td></tr>
		</tbody>
	</table>
	<ul class="pager" id="pager" style="display:none;">
		<li id="previous" class="previous" onclick="previous()"><a href="javascript:void(0)">&larr; 上一页</a></li>
		<li><a class="pager_tip" href="#">第<b id="pageNum"></b>页，命中数：<b id="sizeNum"></b>，检索数：<b id="searchNum"></b>，预估剩余数：<b id="leftNum"></b></a></li>
		<li id="next" class="next" onclick="next()"><a href="javascript:void(0)">下一页 &rarr;</a></li>
	</ul>
</div>
</div>
<!-- 消息轨迹 -->
<div id="trackModal" class="modal fade" tabindex="-1" data-width="400">
	<div class="modal-dialog" id="trackSize">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
				<h4 class="modal-title">消息轨迹</h4>
			</div>
			<div class="modal-body">
				<div id="trackDiv"> </div>
			</div>
		</div>
	</div>
</div>
<!-- 消息重发确认 -->
<div id="resendMsgModal" class="modal fade" tabindex="-1" data-width="400">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
				<h4 class="modal-title">消息重发</h4>
			</div>
			<div class="modal-body text-center" style="word-break:break-all">
				重新发送序号为<b id="dataIdx"></b>的消息?
			</div>
			<div class="modal-footer">
				<button type="button" data-dismiss="modal" class="btn" >取消</button>
				<button type="button" class="btn btn-primary" id="resendMessageBtn" onclick="resendMessage()">确定</button>
			</div>
		</div>
	</div>
</div>
<div id="scriptDiv" style="display:none;"></div>
<script>
var pageNum = 0;
//显示分页
function showPage(num){
	pageNum = num;
	var comp = $("#data_"+num);
	var size = comp.attr("data_size");
	var search = comp.attr("data_search");
	var left = comp.attr("data_left");
	$("#pageNum").html(num);
	$("#sizeNum").html(size);
	$("#searchNum").html(search);
	$("#leftNum").html(left);
	$("#pager").show();
	if(num == 1){
		$("#previous").addClass("disabled");
	} else {
		$("#previous").removeClass("disabled");
	}
	if(left > 0){
		$("#next").removeClass("disabled");
	} else {
		$("#next").addClass("disabled");
	}
	// 展示数据
	$("#page_"+pageNum).show().siblings("tbody").hide();
}
// 上一页
function previous(){
	if(!$("#previous").hasClass("disabled")){
		showPage(pageNum - 1);
	}
}
// 下一页
function next(){
	if(!$("#next").hasClass("disabled")){
		if($("#data_"+(pageNum+1)).length > 0){
			showPage(pageNum+1);
		} else {
			if($("#offsetStart").is(":visible")){
				searchOffsetMessage(true);
			} else {
				searchMessage(true);
			}
		}
	}
}
// 消息搜索
function searchMessage(append){
	$("#append").val(append);
	post('${request.contextPath}/msg/search', $("#msgSearchForm").serialize(), function(data){
		if(!append){
			$("#dataTable tbody").remove();
			$("#dataTable input").remove();
		}
       	$("#dataTable").append(data);
    });
}
//偏移量消息搜索
function searchOffsetMessage(append){
	if(!$("#offsetStart").val()){
		alert("起始偏移量不能为空");
		return;
	}
	if(!$("#offsetEnd").val()){
		alert("结束偏移量不能为空");
		return;
	}
	$("#append").val(append);
	post('${request.contextPath}/msg/offset/search', $("#msgSearchForm").serialize(), function(data){
		if(!append){
			$("#dataTable tbody").remove();
			$("#dataTable input").remove();
		}
       	$("#dataTable").append(data);
    });
}
//消息id搜索
function viewMessage(){
	if(!$("#msgId").val()){
		alert("消息id不能为空");
		return;
	}
	post('${request.contextPath}/msg/id/search', $("#msgSearchForm").serialize(), function(data){
		$("#dataTable tbody").remove();
		$("#dataTable input").remove();
       	$("#dataTable").append(data);
    });
}
// 消息key搜索
function searchKeyMessage() {
	if(!$("#msgKey").val()){
		alert("消息key不能为空");
		return;
	}
	post('${request.contextPath}/msg/key/search', $("#msgSearchForm").serialize(), function(data){
		$("#dataTable tbody").remove();
		$("#dataTable input").remove();
       	$("#dataTable").append(data);
    });
}
// 轨迹
var trackOption = {};
function track(msg){
	if(myTrackChart){
		myTrackChart.dispose();
	}
	msg.cid = $("#cid").val();
	msg.topic = $("#topicDiv").val();
	msg.tid = ${RequestParameters.tid};
	post('${request.contextPath}/msg/track',
		msg,
       	function(data){
			setTrackOption(msg);
			$("#scriptDiv").html(data);
			drawTrackTopology();
	    }
    );
}
function resetSize(size){
	var width = 0;
	var height = 0;
	if(size <= 1){
		width = 800;
		height = 200;
	} else if(size <= 2){
		width = 800;
		height = 400;
	} else {
		width = 1000;
		height = 600;
	}
	$("#trackSize").attr("style", "width:"+width+"px;height:"+height+"px;");
	$("#trackDiv").attr("style", "width:"+(width-20)+"px;height:"+height+"px;");
}
function appendTrackOption(name, status, ex, size, idx){
	var consumerY = 800;
	var symbolSize = 100;
	if(size == 1){
		
	} else if(size == 2){
		symbolSize = 90;
		consumerY = 400;
	} else {
		symbolSize = [80, 28];
		consumerY = 800/size;
	}
	trackOption.series[0].data.push({
        name: name,
        x: 1000,
        y: idx * consumerY + consumerY / 2,
        _tooltip: "consumer",
        symbolSize: symbolSize,
        itemStyle : {
        	normal: {
                color: 'rgb(255,182,13)'
            },
            emphasis: {
                barBorderWidth: 1,
                shadowBlur: 20,
                shadowOffsetX: 0,
                shadowOffsetY: 0,
                shadowColor: 'rgba(0,0,0,0.5)'
            }
        },
        label : {
        	color: '#000',
        	textShadowColor: '#808A87',
        	textShadowBlur : '3'
        }
	});
	
	var color = "#000";
	var fontWeight = "normal";
	if(status.indexOf("消费成功") == -1){
		color = "red";
		fontWeight = "bold";
	}
	trackOption.series[0].links.push({
        source: 1,
        target: idx + 2,
        _tooltip: ex,
        lineStyle : {
            color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                    offset: 0, color: 'rgb(255,182,0)' // 0% 处的颜色
                }, {
                    offset: 1, color: 'rgb(255,182,13)' // 100% 处的颜色
                }],
                globalCoord: false // 缺省为 false
            },
            type : 'dotted'
        },
        label: {
            show: true,
            color : color,
            fontWeight: fontWeight,
            formatter: function (){
            	return status;
            }
        }
    });
}
var myTrackChart = null;
function drawTrackTopology(){
	var dom = document.getElementById("trackDiv");
	myTrackChart = echarts.init(dom);
	myTrackChart.setOption(trackOption, true);
}
$(function(){
	$("[data-toggle='tooltip']").tooltip({container: 'body'});
	//初始化broker列表
 	initBrokerList('brokerNameSearchSelect');
 	$(".selectpicker").selectpicker({
		width : 120
 	});
 	$("#queueSearchSelect").selectpicker('refresh');
});
function setTrackOption(msg){
	trackOption = {
	    tooltip: {
	    	confine: true,
	    	enterable: true,
	    	trigger : 'item',
	    	backgroundColor : 'white',
	    	padding : 0,
	    	textStyle: {
	    		color: 'no',
	    	},
	    	borderWidth: 1,
	    	formatter: function (params, ticket, callback) {
	    		return params.data._tooltip;
	    	}
	    },
	    animationDurationUpdate: 1000,
	    animationEasingUpdate: 'quinticInOut',
	    series : [
	        {
	            type: 'graph',
	            layout: 'none',
	            roam: true,
	            label: {
	                normal: {
	                    show: true
	                }
	            },
	            edgeSymbol: ['circle', 'arrow'],
	            edgeSymbolSize: [4, 10],
	            edgeLabel: {
	                normal: {
	                    textStyle: {
	                        fontSize: 12
	                    }
	                }
	            },
	            data: [
	            {
	                name: msg.client,
	                x: 0,
	                y: 400,
	                symbolSize: 100,
	                _tooltip: "producer",
	                itemStyle : {
	                	normal: {
	                        color: 'rgb(255,99,2)'
	                    },
	                    emphasis: {
	                        barBorderWidth: 1,
	                        shadowBlur: 20,
	                        shadowOffsetX: 0,
	                        shadowOffsetY: 0,
	                        shadowColor: 'rgba(0,0,0,0.5)'
	                    }
	                }
		        },
	            {
	                name: msg.broker,
	                x: 500,
	                y: 400,
	                symbolSize: 150,
	                _tooltip: "broker",
	                itemStyle : {
	                	normal: {
	                    	color: {
	                    	    type: 'linear',
	                    	    x: 0,
	                    	    y: 0,
	                    	    x2: 0,
	                    	    y2: 1,
	                    	    colorStops: [{
	                    	        offset: 0, color: 'rgb(255,99,0)' // 0% 处的颜色
	                    	    }, {
	                    	        offset: 1, color: 'rgb(255,182,0)' // 100% 处的颜色
	                    	    }],
	                    	    globalCoord: false // 缺省为 false
	                    	}
	                    },
	                    emphasis: {
	                        barBorderWidth: 1,
	                        shadowBlur: 20,
	                        shadowOffsetX: 0,
	                        shadowOffsetY: 0,
	                        shadowColor: 'rgba(0,0,0,0.5)'
	                    }
	                }
	            }
	           ],
	            links: [
	            {
	                source: 0,
	                target: 1,
	                _tooltip: "生产时间",
	                lineStyle : {
                    	color: {
                    	    type: 'linear',
                    	    x: 0,
                    	    y: 0,
                    	    x2: 0,
                    	    y2: 1,
                    	    colorStops: [{
                    	        offset: 0, color: 'rgb(255,99,2)' // 0% 处的颜色
                    	    }, {
                    	        offset: 1, color: 'rgb(255,99,0)' // 100% 处的颜色
                    	    }],
                    	    globalCoord: false // 缺省为 false
                    	},
                    	type : 'dotted'
	                },
	                label: {
	                    show: true,
	                    formatter: function (){
	                        return formatDate(msg.born);
	                    }
	                }
	            }
	           	]
	            ,lineStyle: {
	                normal: {
	                    opacity: 0.9,
	                    width: 2,
	                    curveness: 0
	                }
	            }
	        }
	    ]
	};
}

var prevSearchType = "offset";
function changeSearchType(type){
	// 无改变
	if(prevSearchType == type){
		return;
	}
	$("."+type).show();
	if(prevSearchType) {
		$("."+prevSearchType).hide();
	}
	prevSearchType = type;
	
	// 清空数据
	$("#dataTable tbody").remove();
	$("#dataTable").append("<tbody><tr class='no_more_data'><td colspan=7 class='text-center'>暂无数据</td></tr></tbody>");
	$("#dataTable input").remove();
	$("#pager").hide();
	hideAndResetBrokerSelect();
}

function timeChange(id){
	var dt = $("#" + id + "Picker").val();
	var tm = parseDate(dt);
	$("#" + id).val(tm);
}
// 初始化key查询方式的时间
timeChange('keyStartTime');

// 初始化多选
function initMultiSelect(bodyId){
	<#if owner == 1>
		$('#dataTable ' + bodyId).multiSelect();
	</#if>
}

// 重发消息 提示
function resendMessageTip(){
	var dataIdxArray = new Array();
	$('#dataTable tbody tr.selected').each(function(){
		dataIdxArray.push($(this).attr("dataIdx"));
	});
	if(dataIdxArray.length == 0) {
		alert("请先选择消息(支持shift和ctrl)");
		return;
	}
	$("#dataIdx").html(dataIdxArray.toString());
	$('#resendMsgModal').modal('show');
}

//重发消息 
function resendMessage(){
	var dataArray = new Array();
	$('#dataTable tbody tr.selected').each(function(){
		dataArray.push($(this).attr("data"));
	});
	if(dataArray.length == 0) {
		alert("请先选择消息(支持shift和ctrl)");
		return;
	}
	disable("resendMessageBtn");
	$.post('${request.contextPath}/msg/resend',
		{
			msgIds: dataArray.toString(),
			tid: ${RequestParameters.tid}
		},
        function(data){
			enable("resendMessageBtn");
            if(data.status == 200){
            	toastr.success("申请成功！请耐心等待！");  	            	
            	$('#resendMsgModal').modal('hide');       	
		    }else{
		    	toastr.error("申请失败！"+data.message);  
		    }
    }, 'json');
}

//显示搜索条件broker和队列
function showMoreSearchCondition(){
	if ($("#moreSearchCondition").hasClass('hide')){
		$("#moreSearchCondition").removeClass('hide');
	} else {
		hideAndResetBrokerSelect();
	}
}

function hideAndResetBrokerSelect(){
	$("#moreSearchCondition").addClass('hide');
	//重置broker下拉框状态
	document.getElementById("brokerNameSearchSelect").options.selectedIndex = 0; //回到初始状态
    $("#brokerNameSearchSelect").selectpicker('refresh');
}
/**
 * 初始化broker下拉列表
 */
var brokerNameMap = null;
function initBrokerList(componentId){
	$.get('${request.contextPath}/topic/brokerName/list',
			{
				topic: $("#topicDiv").val(),
				clusterId : $("#cid").val()
			},
	        function(data){
	            if(data.status == 200){
	            	brokerNameMap = data.result;
	            	var content = "<option value='all'>全部</option>";
	            	for (var key in brokerNameMap){
	            		content += "<option value='"+key+"'>"+key+"</option>";
	            	}
	        		$("#"+componentId).html(content);
	        		$("#"+componentId).selectpicker('refresh');
			    }else{
			    	toastr.error("数据获取失败！"+data.message);  
			    }
        }, 'json');
}
var maxAllOffset = ${response.result.maxOffset?c};
var minAllOffset = ${response.result.minOffset?c};
var queueOffsetMap = null;
function brokerNameSelectChange(obj){
	var value = obj.options[obj.selectedIndex].value;
	if (value == "all"){
		$("#queueSearchSelect").html("<option value='-1'>全部</option>");
		$("#queueSearchSelect").selectpicker('refresh');
		$("#offsetStart").val(minAllOffset);
		$("#offsetEnd").val(maxAllOffset);
		return;
	}
	resetMaxOffsetByBrokerName(value);
	$.get('${request.contextPath}/consumer/broker/queue',
			{
				topic: $("#topicDiv").val(),
				brokerName: value,
				clusterId : $("#cid").val()
			},
	        function(data){
	            if(data.status == 200){
	            	queueOffsetMap = data.result;
	            	var content = "<option value='-1'>全部</option>";
	            	for (var  key in queueOffsetMap){
	            		content += "<option value='"+key+"'>"+key+"</option>";
	            	}
	            	$("#queueSearchSelect").html(content);
	            	$("#queueSearchSelect").selectpicker('refresh');
			    }
	    }, 'json');
}
function queueSelectChange(obj){
	var value = obj.options[obj.selectedIndex].value;
	var queue = parseInt(value);
	if (queue == -1){
		resetMaxOffsetByBrokerName($("#brokerNameSearchSelect").val());
		return;
	}
	resetMaxOffset(queue, 'queue');
}
//重置偏移量
function resetMaxOffsetByBrokerName(key){
	if (brokerNameMap != null){
		resetMaxOffset(key,'broker');
	}
}
function resetMaxOffset(key,type){
	var max = null;
	if (type == 'broker'){
		max = brokerNameMap[key];
	}else{
		max = queueOffsetMap[key];
	}
	
	var min = max - 100;
	if (min < 0){
		min = 0;
	}
	$("#offsetStart").val(min);
	$("#offsetEnd").val(max);
}
</script>